import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp = null;
    private int serverPort = 0;

    // 服务器 ip 和 端口 也需要告诉客户端. 才能顺利把消息发个服务器
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while (true){
            //1.从控制台读取数据
            System.out.print("=>:");
            String request = scanner.next();
            if (request.equals("exit")){
                System.out.println("goodBye!");
                break;
            }

            //2.构造UDP请求并发送
            //构造这个 Packet 的时候, 需要把 serverIp 和 port 都传入过来，此处 IP 地址需要填写的是一个 32位的整数形式.
            //上述的 IP 地址是一个字符串，需要使用 InetAddress.getByName 来进行一个转换
            DatagramPacket requestPack = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPack);

            //3.读取服务器的UDP响应并解析
            DatagramPacket responsePack = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePack);
            String response = new String(responsePack.getData(),0,responsePack.getLength());

            //4.打印解析的结果
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}